<template>
  <div class="giveMark">
    <div class="testName">
      <div
        class="backBox"
        @click="backBox"
      >
        <el-icon>
          <ArrowLeft />
        </el-icon>
        返回
      </div>

      <h1> {{ paperTestDataStore.paperTitle }}</h1>
    </div>

    <div>
      <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        @select="handleSelect"
      >
        <el-menu-item index="1">全部</el-menu-item>
        <el-menu-item index="2">填空题</el-menu-item>
        <el-menu-item index="3">论述题</el-menu-item>
      </el-menu>
    </div>

    <div class="giveMarkBox">
      <div
        class="fill_question"
        v-if="(fill && !discuss) || fill"
      >
        <div class="question_title">
          <span>四、填空题</span>
          <span>(共 {{ paperTestDataStore.fillChoiceDetail.length }} 题，每小题
            {{ paperTestDataStore.fillChoiceValue }}
            分，共
            {{ paperTestDataStore.fillChoiceDetail.length * paperTestDataStore.fillChoiceValue}}分)</span>
        </div>
        <div
          class="question_content"
          v-for="(item,index) in paperTestDataStore.fillChoiceDetail"
          :key="index"
        >
          <div class="question_t">
            <span>{{index + 1 + '、'+ item.topic }}</span>

            <el-button
              plain
              class="analysisBtn"
              @click="viewParsing(item)"
            >查看解析</el-button>
          </div>
          <div class="question_stem">
            <div class="option">
              <div v-if="item.inputAnswer">
                {{ item.inputAnswer }}
              </div>
              <div
                v-else
                style="color: red;"
              >
                学生未作答
              </div>
            </div>
          </div>
          <div style="margin-top: 24px;margin-left: 40px;">
            <span style="font-size: 18px;color: #209F85;">请输入分数：</span>
            <el-input
              style="width: 141px;height: 35px;border-radius: 6px 6px 6px 6px;border: 1px solid #209F85;"
              v-model="item.giveMarks"
              placeholder="请输入分数"
              @input="inputChange(item)"
              @blur="validateInput(item)"
            ></el-input>
            <span style="font-size: 18px;color: #209F85;">分</span>
            <p
              v-if="item.isErrorMsg"
              class="error-message"
            >{{ item.errorMessage }}</p>
          </div>
        </div>

      </div>

      <div
        class="discuss_question"
        v-if="(!fill && discuss) || discuss"
      >
        <div class="question_title">
          <span>五、论述题</span>
          <span>(共 {{ paperTestDataStore.discussChoiceDetail.length }} 题，每小题
            {{ paperTestDataStore.discussChoiceValue }}
            分，共{{ paperTestDataStore.discussChoiceDetail.length * paperTestDataStore.discussChoiceValue}}分)</span>
        </div>
        <div
          class="question_content"
          v-for="(item,index) in paperTestDataStore.discussChoiceDetail"
          :key="index"
        >
          <div class="question_t">
            <span>{{index + 1 + '、'+ item.topic }}</span>
            <el-button
              plain
              class="analysisBtn"
              @click="viewParsing(item)"
            >查看解析</el-button>
          </div>
          <div class="question_stem">
            <div
              class="option"
              style="height: 150px;"
            >
              <div v-if="item.inputAnswer">
                {{ item.inputAnswer }}
              </div>
              <div
                v-else
                style="color: red;"
              >
                学生未作答
              </div>
            </div>
          </div>
          <div style="margin-top: 24px;margin-left: 40px;">
            <span style="font-size: 18px;color: #209F85;">请输入分数：</span>
            <el-input
              style="width: 141px;height: 35px;border-radius: 6px 6px 6px 6px;border: 1px solid #209F85;"
              v-model="item.giveMarks"
              placeholder="请输入分数"
              @input="inputChange1(item)"
              @blur="validateInput(item)"
            ></el-input>
            <span style="font-size: 18px;color: #209F85;">分</span>
            <p
              v-if="item.isErrorMsg"
              class="error-message"
            >{{ item.errorMessage }}</p>
          </div>
        </div>
      </div>

      <div class="operateBox">
        <el-button
          style="margin-right: 234px;"
          class="cancelBtn"
          plain
          @click="backBox"
        >取消</el-button>
        <el-button
          class="saveBtn"
          plain
          @click="saveMarks"
        >保存</el-button>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref } from 'vue'
import { usePaperTestDataStore } from '@/store/modules/papertestdata.js'
import { useRoute, useRouter } from 'vue-router';
// 引入修改成绩的接口
import { updateScore } from '@/api/assessment/exammanage.js'

import { ElMessage, ElMessageBox } from 'element-plus'
const route = useRoute()
const router = useRouter()
const activeIndex = ref('1')
const paperId = computed(() => route.query.paperId)
const scoreId = computed(() => route.query.scoreId)
// 引入存储成绩详情和试卷详情的pinia仓库
const paperTestDataStore = usePaperTestDataStore()
paperTestDataStore.getPersonScore(scoreId.value)
paperTestDataStore.getTestPaper(paperId.value)



function backBox () {
  router.go(-1)
}

const fill = ref(true)
const discuss = ref(true)
function handleSelect (index) {
  // console.log(index)
  activeIndex.value = index
  // console.log(activeIndex.value)
  if (activeIndex.value == 1) {
    fill.value = true
    discuss.value = true
  } else if (activeIndex.value == 2) {
    fill.value = true
    discuss.value = false
  } else {
    fill.value = false
    discuss.value = true
  }
}




async function saveMarks () {
  let fillChoiceAssessment = 0
  paperTestDataStore.fillChoiceDetail.forEach(item => {
    fillChoiceAssessment += Number(item.giveMarks)
  })

  let discussChoiceAssessment = 0
  paperTestDataStore.discussChoiceDetail.forEach(item => {
    discussChoiceAssessment += Number(item.giveMarks)
  })

  let errMessages1 = []
  const regex = /^(\d+(\.\d{1})?)$/;

  for (let i = 0; i < paperTestDataStore.fillChoiceDetail.length; i++) {
    console.log(paperTestDataStore.fillChoiceDetail[i].giveMarks)

    if (Number(paperTestDataStore.fillChoiceDetail[i].giveMarks) > paperTestDataStore.fillChoiceValue) {
      return ElMessage({
        type: "error",
        message: `第${i + 1}道填空题分数大于每题最大分值，请重新打分。`
      })
    } else if (Number(paperTestDataStore.fillChoiceDetail[i].giveMarks) < 0) {
      return ElMessage({
        type: "error",
        message: `第${i + 1}道填空题得分不能为负值，请重新评分`
      })
    } else if (!regex.test(Number(paperTestDataStore.fillChoiceDetail[i].giveMarks))) {
      return ElMessage({
        type: "error",
        message: `第${i + 1}道填空题评分请输入有效的数字（正整数或一位小数）`
      })
    } else if (parseFloat(Number(paperTestDataStore.fillChoiceDetail[i].giveMarks)) < 0) {
      return ElMessage({
        type: "error",
        message: `第${i + 1}道填空题评分请输入大于等于0的数字`
      })
    } else if (paperTestDataStore.fillChoiceDetail[i].giveMarks == null) {
      return ElMessage({
        type: "error",
        message: `第${i + 1}道填空题评分不能为空`
      })
    } else if (paperTestDataStore.fillChoiceDetail[i].giveMarks == '') {
      return ElMessage({
        type: "error",
        message: `第${i + 1}道填空题评分不能为空`
      })
    }
  }

  let errorMessages2 = []

  for (let i = 0; i < paperTestDataStore.discussChoiceDetail.length; i++) {
    if (Number(paperTestDataStore.discussChoiceDetail[i].giveMarks) > paperTestDataStore.discussChoiceValue) {
      // errMessages1.push(`第${i + 1}道论述题分数大于每题最大分值，请重新打分，并检查后续打分范围是否准确。`)
      return ElMessage({
        type: "error",
        message: `第${i + 1}道论述题分数大于每题最大分值，请重新打分，并检查后续打分范围是否准确。`
      })
    } else if (Number(paperTestDataStore.discussChoiceDetail[i].giveMarks) < 0) {
      // errMessages1.push(`第${i + 1}道论述题题得分不能为负值，请重新评分`)
      return ElMessage({
        type: "error",
        message: `第${i + 1}道论述题题得分不能为负值，请重新评分`
      })
    } else if (!regex.test(Number(paperTestDataStore.discussChoiceDetail[i].giveMarks))) {
      // errMessages1.push(`第${i + 1}道论述题评分请输入有效的数字（正整数或一位小数）`)
      return ElMessage({
        type: "error",
        message: `第${i + 1}道论述题评分请输入有效的数字（正整数或一位小数）`
      })
    } else if (parseFloat(Number(paperTestDataStore.discussChoiceDetail[i].giveMarks)) < 0) {
      // errMessages1.push(`第${i + 1}道论述题评分请输入大于等于0的数字`)
      return ElMessage({
        type: "error",
        message: `第${i + 1}道论述题评分请输入有效的数字（正整数或一位小数）`
      })
    } else if (paperTestDataStore.discussChoiceDetail[i].giveMarks == null) {
      return ElMessage({
        type: "error",
        message: `第${i + 1}道论述题评分不能为空`
      })
    } else if (paperTestDataStore.discussChoiceDetail[i].giveMarks == '') {
      return ElMessage({
        type: "error",
        message: `第${i + 1}道论述题评分不能为空`
      })
    }
  }

  



  let discussChoiceDetail = JSON.stringify(paperTestDataStore.discussChoiceDetail)
  let fillChoiceDetail = JSON.stringify(paperTestDataStore.fillChoiceDetail)

  ElMessageBox.confirm(
    '您确定要保存当前评分吗？保存后，将不可修改',
    '系统提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await updateScore({
        scoreId: scoreId.value,
        discussChoiceDetail,
        fillChoiceDetail,
        performance: 2,
        fillChoiceAssessment,
        discussChoiceAssessment
      })
      ElMessage({
        type: 'success',
        message: '保存成功',
      })
      router.go(-1)
      paperTestDataStore.discussChoiceDetail.forEach(item => {
        item.giveMarks = null
      })
      paperTestDataStore.fillChoiceDetail.forEach(item => {
        item.giveMarks = null
      })
    })
    .catch(() => {
      for (let i = 0; i < paperTestDataStore.discussChoiceDetail.length; i++) {
        console.log(paperTestDataStore.fillChoiceDetail[i].giveMarks)
      }
      for (let i = 0; i < paperTestDataStore.fillChoiceDetail.length; i++) {
        console.log(paperTestDataStore.fillChoiceDetail)
      }

      ElMessage({
        type: 'info',
        message: '取消保存',
      })
      
    })
}

function inputChange (item) {
  console.log(item)
  if (Number(item.giveMarks) > Number(paperTestDataStore.fillChoiceValue)) {
    item.giveMarks = paperTestDataStore.fillChoiceValue
  }
}
const errorMessage = ref("")

function validateInput (item) {
  console.log(item)
  const rounded = Math.round(Number(item.giveMarks) * 10) / 10;
  let flag = Math.abs(Number(item.giveMarks) - rounded) < 1e-10;
  console.log(flag)
  if (!Number.isInteger(Number(item.giveMarks)) && !flag) {
    item.isErrorMsg = true
    item.errorMessage = '请输入有效的数字（正整数或一位小数）';
  } else {
    item.errorMessage = '';
  }
}
function inputChange1 (item) {
  if (Number(item.giveMarks) > Number(paperTestDataStore.discussChoiceValue)) {
    item.giveMarks = paperTestDataStore.discussChoiceValue
  }
}

function viewParsing (item, i) {
  ElMessageBox.alert(item.analysis, '答案解析', {
    buttonSize: 'small',
    center: true,
    confirmButtonText: '知道了',
    confirmButtonClass: 'elmsgConfirmBtn',
    customClass: 'elmsgBox',
  })
}

</script>

<style lang='scss' scoped>
.giveMark {
  background-color: #f5f5f5;
}
.testName {
  display: flex;
  justify-content: center;
  position: relative;
  width: 100%;
  height: 72px;
  background-color: #fff;
  text-align: center;
  border-bottom: 1px solid #eeeeee;
  .backBox {
    display: flex;
    align-items: center;
    position: absolute;
    left: 20px;
    top: 20px;
    cursor: pointer;
    font-size: 16px;
    color: #363636;
  }
  h1 {
    line-height: 72px;
  }
}

::v-deep(.el-menu--horizontal.el-menu) {
  padding-left: 33%;
}

::v-deep(.el-menu-item) {
  font-size: 18px;
  color: #696969;
  margin-right: 100px;
  &:hover {
    background-color: transparent !important;
    color: #696969 !important;
  }
  &:focus {
    background-color: transparent !important;
    color: #696969 !important;
  }
}

::v-deep(.el-menu-item.is-active) {
  font-size: 18px;
  color: #209f85 !important;
  border-bottom: 2px solid #209f85;
}

.giveMarkBox {
  min-height: 800px;
  // margin-top: 24px;
  margin: 24px 80px 93px 80px;
  background-color: #fff;
  border-radius: 6px 6px 6px 6px;
  padding: 32px 210px;
  .operateBox {
    display: flex;
    justify-content: center;
    margin-top: 50px;
    .cancelBtn {
      width: 120px;
      height: 32px;
      border-radius: 6px 6px 6px 6px;
      border: 1px solid;
      font-size: 14px;
      color: #363636;
    }
    .saveBtn {
      width: 120px;
      height: 32px;
      border-radius: 6px 6px 6px 6px;
      background: linear-gradient(180deg, #209f85 0%, #28b460 100%);
      font-size: 14px;
      color: #ffffff;
    }
  }
}
.question_title {
  display: flex;
  align-items: center;
  margin-top: 48px;
  padding-left: 30px;
  width: 1200px;
  height: 72px;
  background-color: #e9f6f3;
  border: 1px dashed #bdc0bf;
  span:nth-child(1) {
    font-size: 22px;
    color: #363636;
    font-weight: bold;
  }
  span:nth-child(2) {
    font-size: 18px;
    color: #696969;
    margin-left: 8px;
  }
}

.question_content {
  padding: 24px 0 40px 0;
  // border-bottom: 1px solid rgba(0, 0, 0, 0.1);

  .question_t {
    width: 1200px;
    display: flex;
    justify-content: space-between;
    .analysisBtn {
      width: 120px;
      height: 32px;
      border-radius: 6px 6px 6px 6px;
      border: 1px solid rgba(32, 159, 133, 1);

      color: #363636;
      &:hover {
        background-color: transparent;
        // color: #fff !important;
      }
      &:focus {
        background-color: transparent;
        // color: #fff !important;
      }
    }
  }
  span {
    font-size: 18px;
    color: #363636;
    margin-left: 15px;
  }
  .question_stem {
    padding: 0px 0 0 40px;

    .option {
      display: flex;
      justify-content: space-between;
      width: 1160px;
      height: 48px;
      margin-top: 23px;
      padding-left: 32px;
      padding-right: 32px;
      line-height: 48px;
      border-radius: 14px 14px 14px 14px;
      border: 1px solid #209f85;
      span {
        font-size: 16px;
        color: #696969;
      }
    }

    .rightOption {
      background-color: #209f85;
      color: #fff !important;
    }

    .errorOption {
      background-color: #ea6070;
      border: none;
    }
  }

  .error-message {
    color: red;
    margin-top: 5px;
  }
}

::v-deep(.el-message-box__btns) {
}

::v-deep(.el-input__wrapper) {
  box-shadow: none;
}

::v-deep(.el-message-box__footer button.elmsgConfirmBtn) {
  background-color: #28b460 !important;
  font-size: 120px !important;
}

.elmsgConfirmBtn {
  background-color: #28b460;
}

.el-message-box__header {
  font-size: 14px;
}
</style>
